<template>
    <view class="container">
        <u-loading-page :loading="loading > 0" loading-text="正在上传中..." class="u_loading_page"></u-loading-page>
        <view class="upload_type">
            <text>课程名称:</text>
            <u--input
                    placeholder="请输入课程名称"
                    disabled
                    clearable
                    v-model="course.folderName"
                    @blur="handleBlur"
            ></u--input>
        </view>
        <view class="upload_type">
            <text>作者名称:</text>
            <u--input
                    disabled
                    placeholder="请输入作者名称"
                    clearable
                    v-model="course.author"
            ></u--input>
        </view>
        <view class="upload_type upload_type_introduction">
            <view>课程简介:</view>
            <u--textarea
                    disabled
                    v-model="course.introduction"
                    placeholder="请输入课程简介"
                    count
            ></u--textarea>
        </view>
        <view class="video_model">
            <view class="video_model_title"><image src="../../static/images/fileManage/file_manage_tree.svg"></image>视频组菜单：</view>
            <Tree
                    v-if="tableData && tableData.length > 0"
                    ref="tree"
                    :range="tableData"
                    :rangeKey="rangeKey"
                    :idKey="idKey"
                    :title="title"
                    :selectParent="selectParent"
                    :multiple="multiple"
                    :foldAll="flod"
                    :methods="methods"
                    @handleUpdate="handleUpdate"
                    @handleFileInfo="handleFileInfo"
                    @handlePlayer="handlePlayer"
                    @getInfo="getInfo"
                    :isShow="false"
            />
        </view>
    </view>
</template>

<script>
import config from '@/config'
import Tree from '@/components/tree/updateTree.vue'
export default {
    components: {
        Tree,
    },
    data() {
        return {
            loading: 0,
            course: {
                folderName: '',
                author: '',
                introduction: '',
                fileType: '',
                profession: ''
            },
            id: '',
            // 选中的结果
            result: null,
            tableData: [],
            rangeKey: 'chapterName',

            // 指定 Object 中 key 的值作为单条数据的唯一id
            // 跟上面的类似,一个道理，只不过这个是标识的唯一id键名
            idKey: "id",

            // 是否多选(默认单选)
            multiple: false,

            // 是否可以选父级(默认不可选)
            selectParent: false,

            // 折叠时关闭所有已经打开的子集 再次打开时需要一级一级打开
            // 默认不关闭已打开的子集
            flod: false,

            // 标题
            title: "这是标题",
			token: '',
            methods: '',// videoPlayer 视频播放  videoUpdate 视频更新
            folderId: '',
            origin: ''
        }
    },
	onLoad: function (option) {
		const uploadForm = JSON.parse(decodeURIComponent(option.uploadForm))
        this.methods = uploadForm.methods
		this.course.fileType = uploadForm.fileType
		this.course.profession = uploadForm.profession
        this.id = uploadForm.id
        this.folderId = uploadForm.folderId
        this.origin = uploadForm.origin || ''
		console.log('ffff',uploadForm)
		this.token = uni.getStorageSync('token')
        if (this.course && this.id) {
            this.getInfo()
        }
	},
    watch: {
        'course.folderName'(newVal, oldVal) {
            if (newVal != oldVal) {
                if (this.tableData.length === 0) {
                    this.tableData.push({
                        chapterName: newVal,
                        // id: Date.now(),
                        chapter: Date.now(),
                        parentId: null,
                        level: 1,
                    });
                } else {
                    this.tableData.map((item) => {
                        if (item.parentId === null) {
                            this.$set(item, 'chapterName', newVal)
                        }
                    })
                }
                // this.$refs.tree._initTree(this.tableData)
            }
        }
    },
    methods: {
        handleBlur() {
            if (this.course.folderName) {
                this.$refs.tree._initTree(this.tableData)
            }
        },
        getInfo() {
            let that = this
            that.$request({
                url: this.origin ? '/knowledgeTrain/detail' : '/knowledgeFile/video/detail',
                method: 'get',
                params: {
                    id: that.folderId || that.id,
                },
            }).then(({ data }) => {
                that.course = data.course
                that.tableData[0] = data.video
                this.$forceUpdate();
            })
        },
        //视频播放
        handlePlayer(row) {
            console.log(row,'视频播放')
            if (row.videoType === 1) {
                this.$tab.navigateTo(`/pages/player?info=${encodeURIComponent(JSON.stringify(row))}&showCollects=false`)
            } else {
                this.$tab.navigateTo(`/pages/preview?info=${encodeURIComponent(JSON.stringify(row))}&showCollects=false`)
            }
        },
        handleFileInfo(parentRow, row) {
            this.$tab.navigateTo(`/pages/fileManage/fileInfo?item=${encodeURIComponent(JSON.stringify(row))}`);
        },
        //视频更新
        handleUpdate(parentRow, row) {
            console.log(row, 'rowrowrow')
            let fileType = row.fileName.substring(row.fileName.lastIndexOf('.')+1).toLowerCase()
            let that = this
            if (fileType !== 'ppt' && fileType !== 'pptx' && fileType !== 'pdf') {
                uni.chooseVideo({
                    sourceType: ['camera', 'album'],
                    success: function (res) {
    
                        if (res.size > 3 * 1024 * 1024 * 1024) {//3GB
                            that.$toast("仅支持大小为3GB以内的文件");
                            return;
                        }
                        self.src = res.tempFilePath
                        that.loading++
                        uni.uploadFile({
                            url: config.baseUrl + '/file/upload',
                            header: {
                                token: that.token,
                            },
                            filePath: res.tempFilePath,
                            name: 'file',
                            formData: {
                                fileType: that.course.fileType,
                                profession: that.course.profession
                            },
                            success: (uploadFileRes) => {
                                that.loading--
                                let tempData = JSON.parse(uploadFileRes.data)
                                /*if (tempData.data.uploadStatus === 1) {
                                    this.$modal.loading('文件名重复，不可导入！')
                                    setTimeout(()=> {
                                        this.$modal.closeLoading()
                                    }, 1000)
                                    return true
                                }*/
                                console.log(parentRow.videoList, 'row.videoList')
                                /*parentRow.videoList = parentRow.videoList.filter(item => item.id !== row.id)
                                parentRow.videoList.push({
                                    ...tempData.data,
                                    chapter: tempData.data.id || Date.now()
                                })*/
                                that.updateNodeInTree(that.tableData, parentRow.id, parentRow)
                                that.sureFn(tempData.data.id)
                            },
                            fail: (uploadFileError) => {
                                // 处理上传失败的错误
                                that.loading--
                            }
                        })
                    }
                });
            } else {
                uni.chooseFile({
                    count: 1, //默认100
                    extension:['.ppt','.pptx','.pdf'],
                    success: function (res) {
    
                        if (res.tempFiles && res.tempFiles.length > 0 && res.tempFiles[0].size > 2 * 1024 * 1024 * 1024) {//1GB
                            that.$toast("仅支持大小为1GB以内的文件");
                            return;
                        }
                        uni.uploadFile({
                            url: config.baseUrl + '/file/upload',
                            header: {
                                token: that.token,
                            },
                            filePath: res.tempFilePaths[0],
                            name: 'file',
                            formData: {
                                fileType: that.course.fileType,
                                profession: that.course.profession
                            },
                            success: (uploadFileRes) => {
                                let tempData = JSON.parse(uploadFileRes.data)
                                /*if (tempData.data.uploadStatus === 1) {
                                    this.$modal.loading('文件名重复，不可导入！')
                                    setTimeout(()=> {
                                        this.$modal.closeLoading()
                                    }, 1000)
                                    return true
                                }*/
                                console.log(parentRow.videoList, 'row.videoList')
                                /*parentRow.videoList = parentRow.videoList.filter(item => item.id !== row.id)
                                parentRow.videoList.push({
                                    ...tempData.data,
                                    chapter: tempData.data.id || Date.now()
                                })*/
                                that.updateNodeInTree(that.tableData, parentRow.id, parentRow)
                                that.sureFn(tempData.data.id)
                            },
                            fail: uploadFileError => {
                                // 处理上传失败的错误
                            }
                        })
                    }
                })
            }
        },
        //通过id找到对应的节点，将obj挂在该节点上
        updateNodeInTree(treeList,id, obj) {
            if (!treeList || !treeList.length) {
                return
            }
            for (let i = 0; i < treeList.length; i++) {
                if (treeList[i].id === id) {
                    // treeList[i] = obj
                    treeList[i] = {
                        ...treeList[i],
                        ...obj
                    }
                    break
                }
                this.updateNodeInTree(treeList[i].children,id,obj)
            }
        },
        emptyFn() {
            this.tableData = []
            this.course.folderName = ''
            this.course.author = ''
            this.course.introduction = ''
        },
        traverseTree(data) {
            if (!data) return
        
            for (let i = 0; i < data.length; i++) {
                // 处理当前节点
                if (data[i].parentId && typeof data[i].parentId !== 'string' && typeof data[i].parentId !== 'number') {
                    data[i].parentId = data[i].parentId.map(item => {
                        return item
                    }).join(',')
                }
                // 递归遍历子节点
                this.traverseTree(data[i].children)
            }
        },
        sureFn(fileId) {
            //修改parentId为字符串
            this.traverseTree(this.tableData)
            this.$request({
                url: '/knowledgeFile/file/update',
                method: 'post',
                data: {
                    ...this.course,
                    fileId: fileId,
                    id: this.id
                },
            }).then(({ data }) => {
                uni.showToast({
                    title: '更新成功！',
                    icon: 'success',
                    duration: 1000
                })
                // uni.$emit('returnData', this.processList)
                uni.$emit('returnData')
                setTimeout(function() {
                    uni.navigateBack()
                }, 1000)
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.container {
    height: calc(100vh - 88rpx);
    padding: 32rpx 30rpx;
    overflow: auto;
    
    .upload_type {
        min-height: 100rpx;
        border-radius: 16rpx;
        background: #FFFFFF;
        width: 100%;
        display: grid;
        grid-template-columns: 130rpx 1fr;
        grid-template-gap: 30rpx;
        align-items: center;
        padding: 30rpx;
        font-family: 思源黑体;
        font-size: 30rpx;
        color: #1C2126;
        &+.upload_type{
            margin-top: 20rpx;
        }
        ::v-deep {
            .u-input__content__field-wrapper__field{
                text-align: right !important;
                color: #4C5A67!important;
                font-size: 30rpx!important;
            }
            .u-input, .u-textarea{
                border: none;
                background: #FFFFFF !important;
            }
        }
        &.upload_type_introduction{
            grid-template-columns: 1fr;
            grid-row-gap: 20rpx;
            ::v-deep{
                .u-textarea{
                    padding: 0;
                }
                .u-textarea__field {
                    font-family: Source Han Sans;
                    font-size: 30rpx;
                    color: #1C2126;
                }
            }
        }
    }
    
    .bottom {
        width: 100%;
        display: flex;
        justify-content: space-between;
        position: absolute;
        bottom: 40rpx;
        left: 0;
        
        .u-button {
            width: 40%;
        }
    }

    .video_model {
        border-radius: 16rpx;
        background: #FFFFFF;
        margin-top: 40rpx;
        padding: 30rpx;
        .video_model_title{
            display: grid;
            grid-template-columns: 36rpx  1fr;
            grid-column-gap: 20rpx;
            font-family: Source Han Sans;
            font-size: 32rpx;
            font-weight: 500;
            color: #1C2126;
            image{
                width: 36rpx;
                height: 34rpx;
            }
        }
    }
}
</style>